//
//  ZLQSearchController.swift
//  GoTravel
//
//  Created by lanou3g on 16/3/7.
//  Copyright © 2016年 SHH. All rights reserved.
//

import UIKit

typealias Block = (_ :String)->Void

class ZLQSearchController: UITableViewController,UISearchBarDelegate,UISearchControllerDelegate {
    
    var passBlock:Block?
    
    var footerV:UIView = UIView()
    
    var imageBackground = UIImageView()
    
    let kSearchURL = "http://q.chanyouji.com/api/v1/districts/search.json?latitude=0&longitude=0&name="
    
    var string:String?
    
    var dataAray = NSMutableArray()
    var resultArray = NSMutableArray()
    var mySC:UISearchController?
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        self.view.backgroundColor = UIColor.whiteColor()
        self.navigationItem.title = "搜索地点"
        
        tableView.registerClass(ZLQSearchCell.classForCoder(), forCellReuseIdentifier: "cell")
        
//        self.view.alpha = 0.3
        
        imageBackground.frame = self.view.bounds
        imageBackground.image = UIImage(named: "ac11e1ac003ba69dd8893305286915d9.jpg")
        imageBackground.alpha = 0.3
        self.view.addSubview(imageBackground)
        
        
        mySC = UISearchController(searchResultsController: nil)
        mySC?.searchBar.sizeToFit()

//           mySC?.searchBar.frame = CGRectMake(0,50, self.view.frame.size.width, 60)
        self.tableView.tableHeaderView = mySC?.searchBar
     
        
//        self.view.addSubview((mySC?.searchBar)!)
        mySC?.searchBar.delegate = self
        mySC?.delegate = self
//        mySC?.searchResultsUpdater = self
        
//        footerV.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height*0.5)
//        footerV.backgroundColor = UIColor.redColor()
//        self.tableView.tableFooterView = footerV
        
        
        
    }
    
    
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        
        self.dataAray.removeAllObjects()
        
        let characterSet:NSCharacterSet = NSCharacterSet.letterCharacterSet()
        let string:NSString = (searchBar.text?.stringByAddingPercentEncodingWithAllowedCharacters(characterSet)
            )!
        
        
        let urlString = kSearchURL + (string as String)
        print("=======================\(urlString)")
//        let urlS:NSURL = NSURL(string: urlString)!
        let session:NSURLSession = NSURLSession.sharedSession()
        
        let task = session.dataTaskWithURL(NSURL(string: urlString)!) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
            do {
//                let dic:NSDictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
                let dic = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
                
                for  dict in (dic["data"]as! NSArray) {
                    
                    let model:ZLQsearchModel = ZLQsearchModel()
                    model.setValuesForKeysWithDictionary(dict as! [String : AnyObject])
                    print("====================\(model.hint_name!)")
                    self.dataAray.addObject(model)
                }
                
                
            } catch {
                
            }
            
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                
                self.tableView.reloadData()
                
            })
        }
        
        task.resume()
    }


    func didDismissSearchController(searchController: UISearchController) {
        resultArray = dataAray
        print("================\(resultArray)")
        self.tableView.reloadData()
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return dataAray.count
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return self.view.frame.size.height*0.07
    }

   
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as? ZLQSearchCell
        
        
        let model:ZLQsearchModel = self.dataAray[indexPath.row] as! ZLQsearchModel
        cell!.textLabel?.text = model.hint_name!
        string = cell?.textLabel?.text

        return cell!
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
          print(string!)
         self.passBlock!(string!)
        self.navigationController?.popViewControllerAnimated(true)
        
        
    }
  

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
